package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author zzw
 * @date 2025-05-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 入住申请
     *
     * @param checkInApplyDto 入住申请信息
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 1.校验老人是否已入住
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(
                Elder::getIdCardNo, checkInApplyDto
                        .getCheckInElderDto()
                        .getIdCardNo()
                                                                              ));

        if (ObjectUtils.isNotEmpty(elder) && elder.getStatus() == 1) {
            throw new BaseException("该老人已入住");
        }

        // 2.更新床位状态为已入住
        Bed bed = bedMapper.selectOne(new LambdaQueryWrapper<Bed>().eq(
                Bed::getId, checkInApplyDto
                        .getCheckInConfigDto()
                        .getBedId()
                                                                      ));
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 3.新增或更新老人
        elder = insertOrUpdateElder(checkInApplyDto.getCheckInElderDto(), bed);

        // 4.新增签约办理
        saveContract(checkInApplyDto, elder);

        // 5.新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder);

        // 6.新增入住配置
        saveCheckInConfig(checkInApplyDto, checkIn);
    }

    /**
     * 新增或更新老人信息
     *
     * @param checkInElderDto 老人信息
     * @param bed             床位信息
     * @return 老人信息
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);

        // 如果老人不存在，则新增，已存在，则更新
        Elder elderDb = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(
                Elder::getIdCardNo,
                checkInElderDto.getIdCardNo()
                                                                                ));
        if (ObjectUtils.isEmpty(elderDb)) {
            elderMapper.insert(elder);
        } else {
            elderMapper.updateById(elder);
        }
        return elder;
    }

    /**
     * 新增签约办理
     *
     * @param checkInApplyDto 入住申请信息
     * @param elder           老人信息
     */
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        // 设置合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());

        // 设置老人信息
        contract.setElderId(elder
                                    .getId()
                                    .intValue());
        contract.setElderName(elder.getName());

        // 设置入住信息
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        Integer status = checkInConfigDto
                .getStartDate()
                .isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);

        contractMapper.insert(contract);
    }

    /**
     * 新增入住信息
     *
     * @param checkInApplyDto 入住申请信息
     * @param elder           老人信息
     * @return 入住信息
     */
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder) {
        CheckIn checkIn = new CheckIn();

        // 设置老人信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());

        // 设置入住信息
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);

        checkInMapper.insert(checkIn);

        // 老人入住后，要更新健康评估表中老人的入住状态为已入住
        healthAssessmentMapper.update(
                null,
                new LambdaUpdateWrapper<HealthAssessment>().eq(HealthAssessment::getIdCard, elder.getIdCardNo())
                                                           .set(HealthAssessment::getAdmissionStatus, 0)
                                     );

        return checkIn;
    }

    /**
     * 新增入住配置
     *
     * @param checkInApplyDto 入住申请信息
     * @param checkIn         入住信息
     */
    private void saveCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);

        checkInConfig.setCheckInId(checkIn.getId());

        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 入住详情
     *
     * @param id 入住id
     * @return 入住详情
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        // 查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        if (ObjectUtils.isEmpty(checkIn)) {
            throw new BaseException("入住信息不存在");
        }

        // 查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        if (ObjectUtils.isNotEmpty(elder)) {
            BeanUtils.copyProperties(elder, checkInElderVo);
            // 计算年龄
            // Period period = Period.between(LocalDate.parse(elder.getBirthday()), LocalDate.now());
            checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        }

        // 查询家庭成员
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);

        // 查询入住配置
        CheckInConfig checkInConfig =
                checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(
                        CheckInConfig::getCheckInId,
                        checkIn.getId()
                                                                                        ));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        if (ObjectUtils.isNotEmpty(checkInConfig)) {
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
            checkInConfigVo.setStartDate(checkIn.getStartDate());
            checkInConfigVo.setEndDate(checkIn.getEndDate());
            checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        }

        //  查询签约办理
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(
                Contract::getElderId,
                elder.getId()
                                                                                          ));

        // 组装返回数据
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }
}
